﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.LookAndFeel;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;
using XCI.Sys.Filter;
using XCI.Sys.Model;
using XCI.Sys.Service;
using XCI.Windows;

namespace XCI.Sys.Forms
{
    public partial class FormTest3 : BaseForm
    {
        public FormTest3()
        {
            InitializeComponent();
            SplashScreenHelper.Hide();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            gridControl.ModelType = typeof(SysRole);
            //popupContainerEdit1.EditValue = 2;
        }

        private void GridControlPlus1_LoadData(object sender, Windows.LoadDataEventArgs e)
        {
            if (EditRecord != null)
            {
                e.Task = () =>
                {
                    var list = new List<SysRole>();
                    list.Add((SysRole)EditRecord);
                    IPagingList plist = new PagingList<SysRole>(list);
                    return Task.FromResult(plist);
                };
            }
            else
            {
                var roleFilter = new SysRoleFilter();
                roleFilter.CombinePageFilter(e.PageFilter);
                roleFilter.Key = filterEdit.Text.Trim();
                e.Task = async () => await SysRoleService.Instance.SelectPageListAsync(roleFilter);
            }
        }
        private object Selected { get; set; }
        private object EditRecord { get; set; }
        private void GridControlPlus1_DetectFilter(object sender, Windows.DetectFilterEventArgs e)
        {
            e.Filter = new PopupPagingGridFilter();
        }

        private object prveEditValue;
        private string prveDisplayText;

        private void PopupContainerEdit1_QueryDisplayText(object sender, DevExpress.XtraEditors.Controls.QueryDisplayTextEventArgs e)
        {
            if (e.EditValue == prveEditValue)
            {
                e.DisplayText = prveDisplayText;
            }
            else if (Selected != null)
            {
                e.DisplayText = prveDisplayText = ((SysRole)Selected).Name;
                prveEditValue = e.EditValue;
                Debug.WriteLine("QueryDisplayText:" + e.EditValue);
            }
            else if (EditRecord != null)
            {
                e.DisplayText = prveDisplayText = ((SysRole)EditRecord).Name;
                prveEditValue = e.EditValue;
                Debug.WriteLine("QueryDisplayText:" + e.EditValue);
            }
        }

        private void PopupContainerEdit1_QueryResultValue(object sender, DevExpress.XtraEditors.Controls.QueryResultValueEventArgs e)
        {
            if (Selected is SysRole role)
            {
                e.Value = role.Id;
            }
        }

        private void ButtonEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                // ConfirmSelection();
                Selected = gridControl.Selected;
                popupContainerEdit1.ClosePopup();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Delete)
            {
                ClearSelection();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Up)
            {

                gridView.MovePrev();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Down)
            {

                gridView.MoveNext();
                e.Handled = true;
            }
        }

        private void GridControlPlus1_AfterInitialize(object sender, EventArgs e)
        {
            gridView.PaintAppearance.HideSelectionRow.BackColor = gridView.PaintAppearance.FocusedRow.BackColor;
        }

        private async void ButtonEdit1_EditValueChanged(object sender, EventArgs e)
        {
            await gridControl.LoadFirstPageAsync();
        }

        private async void Button2_Click(object sender, EventArgs e)
        {
            EditRecord = await SysRoleService.Instance.SelectByIdAsync("1307293566229417984");
            popupContainerEdit1.EditValue = 1307293566229417984;
            OnceAction.Remove("LoadData");
            //var frm = new FrmSettingThemeForm();
            //frm.ShowDialog();
            //frm.Dispose();
        }


        private async void PopupContainerEdit1_Popup(object sender, EventArgs e)
        {
            await OnceAction.RunAsync("load data", () =>
            {
                return gridControl.LoadFirstPageAsync();
            });
        }

        private Pen pen;
        private void ButtonEdit1_Paint(object sender, PaintEventArgs e)
        {
            if (DesignMode) return;
            var isDarkSkin = DevExpress.Utils.Frames.FrameHelper.IsDarkSkin(UserLookAndFeel.Default);
            if (pen == null) pen = isDarkSkin ? new Pen(Color.FromArgb(75, 75, 75)) : new Pen(Color.FromArgb(200, 200, 200));
            e.Graphics.DrawLine(pen, 0, filterEdit.Height - 1, Width, filterEdit.Height - 1);
        }

        private void GridControlPlus1_ProcessGridKey(object sender, KeyEventArgs e)
        {
            if (gridView.IsGroupRow(gridView.FocusedRowHandle)) return;

            if (e.KeyCode == Keys.Enter)
            {
                Selected = gridControl.Selected;
                popupContainerEdit1.ClosePopup();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Delete)
            {
                ClearSelection();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Up)
            {
                gridView.MovePrev();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Down)
            {
                gridView.MoveNext();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Back)
            {
                if (Text.Length <= 0) return;
                filterEdit.Text = filterEdit.Text.Remove(filterEdit.Text.Length - 1);
                FocusCore();
                e.Handled = true;
            }
            else if ((e.KeyValue >= 65 && e.KeyValue <= 90)//A-Z
                     || (e.KeyValue >= 97 && e.KeyValue <= 122)//a-z
                     || (e.KeyValue >= 48 && e.KeyValue <= 57))//0-9
            {
                filterEdit.Text += Convert.ToChar(e.KeyValue).ToString().ToLower();
                FocusCore();
                e.Handled = true;
            }
        }
        protected void FocusCore()
        {
            if (!filterEdit.Focused)
            {
                filterEdit.Focus();
                if (Text != null) filterEdit.SelectionStart = Text.Length;
            }
        }

        protected async void ClearSelection()
        {
            Selected = null;
            EditRecord = null;

            if (string.IsNullOrEmpty(filterEdit.Text))
            {
                await gridControl.LoadFirstPageAsync();
            }
            else
            {
                filterEdit.Text = string.Empty;
            }
        }
    }

    public class PopupPagingGridFilter : BasePageFilter
    {
        public string Key { get; set; }
    }
}
